package cn.zhxu.data.fastjson2;

import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.writer.ObjectWriter;

import java.lang.reflect.Type;
import java.time.format.DateTimeFormatter;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalAccessor;

public class TemporalWriter implements ObjectWriter<Temporal> {

    private final DateTimeFormatter defaultFormatter;

    public TemporalWriter(String defaultFormat) {
        defaultFormatter = DateTimeFormatter.ofPattern(defaultFormat);
    }

    @Override
    public void write(JSONWriter writer, Object object, Object fieldName, Type fieldType, long features) {
        if (object == null) {
            writer.writeNull();
            return;
        }
        String format = Fastjson2DataConvertor.FORMAT_HOLDER.get();
        if (format != null) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
            writer.writeString(formatter.format((TemporalAccessor) object));
        } else {
            writer.writeString(defaultFormatter.format((TemporalAccessor) object));
        }
    }

}
